
//搜索用的数据
var _Query_Data = {

    per_page : 100,

    page : 1

};


//vue的data
var _Global_Data = {

    glass_type : {

        0 : '近视镜',

        1 : '太阳镜',

        2 : '功能镜'

    },                          //眼镜类型映射表

    type_name : {

        'Glass' : '镜框',

        'Lens' : '镜片',

        'BeautyContactLens' : '彩色隐形眼镜',

        'TransparentContactLens' : '透明隐形眼镜',

        'NursingSupply' : '护理用品'

    },                          //眼镜的分类名字

    query_info : _Query_Data,   //搜索所用数据

    search_info : {},           //改变页数使用的搜索数据

    all_products : {},          //全部现有的商品

    frame_types : [],           //眼镜框型

    brands : [],                //品牌

    funcs : [],                 //功能类型

    func_types : [],            //功能镜类型

    materials : [],             //材质

    frames : [],                //试戴素材

    colors : [],                //颜色

    styles : [],                //风格

    genders : [],               //性别

    lenses : [],                //镜片

    opto : {},                  //验光数据

    selected_color_ids : [],       //多选框选中的颜色id数组

    selected_colors : [],       //拼接成的颜色数组

    products : {},              //当前种类的眼镜列表详情

    current_glass : {

        colors : []

    },         //当前查看的眼镜详情

    combine_products : [
        {
            customer_type : '',

            product_type : '',

            relate_product_id : '',

            color_id : '',

            sale_price : 0,

            count : 0,

            max_count : 0,

            current_product_all : {},       //组合镜片的所有商品

            current_product : null,           //当前对应类型可选的商品

            current_product_type : [],     //可选的眼镜类型

            current_colors : []             //可选的颜色
        }
    ],                          //组合镜片数组

    sup_product : null,           //用于承接供应商返回的全部商品

    watching_detail : false,    //是否在查看详情

    show_func_type : false,     //显示方法类型

    has_rd : false,             //是否包含度数

    has_product : false,            //是否包含组合商品

    is_supplier : false,             //是否为供应商修改

    supplier_power : false          //是否为供应商权限添加

};

//眼镜
var glassResource = new Resource( API_LIST.GLASS_LIST , Vue.http );
//请求颜色
var ProductColorResource = new Resource( API_LIST.AISLE_PRODUCT_COLOR , Vue.http);

!function glassControl(){

     var vm = new Vue({

        el: "#glass_type",

        data: _Global_Data,


        created : function(){

            this.initGlassData()
                .then(this.getGlassList(this.query_info))

        },

        methods: {
            //组合镜片中获取customer_type的方法
            getCustomerType : function getCustomerType( index , e){

                var self = this;

                self.combine_products[index].current_product_type = [];

                self.combine_products[index].customer_type = e.target.value;

                if( parseInt(e.target.value) === 1 ){

                    if( self.combine_products[index].current_product_all ){

                        var params = {

                            customer_type : 1

                        };

                        if( self.sup_product ){

                            var json_object = JSON.stringify(self.sup_product);

                            self.combine_products[index].current_product_all = JSON.parse(json_object);

                        }else {

                            self.combineGlassType( index , params )
                                .then(function(){

                                    var json_object = JSON.stringify(self.sup_product);

                                    self.combine_products[index].current_product_all = JSON.parse(json_object);

                                })

                        }

                    }

                }else {

                    var json_object = JSON.stringify(self.all_products);

                    self.combine_products[index].current_product_all = JSON.parse(json_object);

                    // $('.product_type').eq(2*index+1).val(self.combine_products[index].current_product_type[0]).trigger('change');

                }

                for( var key in self.combine_products[index].current_product_all ){

                    if( self.combine_products[index].current_product_all[key].length > 0 ){

                        self.combine_products[index].current_product_type.push(key);

                    }

                }

                $('.product_type').eq(2*index+1).val('').trigger('change');

            },

            //组合镜片中获取product_type的方法
            getRelateType : function getRelateType( index , e ){

                this.combine_products[index].product_type = e.target.value;

                this.combine_products[index].current_product = this.combine_products[index].current_product_all[e.target.value];

                // $('.relate_product').eq(2*index+1).val(this.combine_products[index].current_product[0].id).trigger('change');

            },

            //组合镜片中获取relate_product的方法
            getRelateProduct : function getRelateProduct( index , e ){

                var self = this;

                var selected_product = self.combine_products[index].current_product.filter(function(product){

                    return product.id == e.target.value;

                })[0];

                self.combine_products[index].relate_product_id = e.target.value;

                self.combine_products[index].sale_price = selected_product.promotion_sale_price;

                self.combineGlassColor(index);

            },

            //组合镜片中获取color_id的方法
            getColorId : function getColorId( index , e ){

                this.combine_products[index].color_id = e.target.value;

            },

            //增加组合镜片的方法
            newLensAdd : function newLensAdd(){

                var new_len = {

                    customer_type : '',

                    product_type : '',

                    relate_product_id : '',

                    color_id : '',

                    sale_price : 0,

                    count : 0,

                    max_count : 0,

                    current_product_all : {},

                    current_product : null,

                    current_product_type : [],

                    current_colors : []
                };

                this.combine_products.push( new_len );

            },

            //删除组合镜片的方法
            lensDelete : function lensDelete( index ){

                this.combine_products.splice( index , 1 );

            },

            //组合镜片切换请求商品类别的方法
            combineGlassType : function combineGlassType( index , params ){

                var self = this;

                App.blockUI('#product_single');

                return glassResource.create(params)
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            self.sup_product = res.data.all_products;

                                        } else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#product_single');

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        App.unblockUI('#product_single');

                                        alert('网络异常！');

                                    })

            },

            //组合镜片选择商品请求对应的颜色的方法
            combineGlassColor : function combineGlassColor( index ){

                var self = this;

                var params = {

                    product_id : self.combine_products[index].relate_product_id,

                    product_type : self.combine_products[index].product_type

                };

                App.blockUI('#product_single');

                return ProductColorResource.index( params )
                                            .then(function (res) {

                                                if (parseInt(res.data.code) === 0) {

                                                    self.combine_products[index].current_colors = res.data.colors;

                                                } else {

                                                    alert(res.data.error);

                                                }

                                                App.unblockUI('#product_single');

                                            })
                                            .catch(function (err) {

                                                console.log(err);

                                                App.unblockUI('#product_single');

                                                alert('网络异常！');

                                            })

            },

            //清空日期的方法
            resetTime: function resetTime(id) {

                this.$refs[id].value = '';

            },

            //重置所有表单数据的方法
            resetAllData : function resetAllData(){

                this.current_glass.colors = null;

                this.current_glass.thumb_img = null;

                this.watching_detail = false;

                this.show_func_type = false;

                this.has_rd = false;

                this.has_product = false;

                this.is_supplier = false;

                this.combine_products = [
                    {
                        customer_type : '',

                        product_type : '',

                        relate_product_id : '',

                        color_id : '',

                        sale_price : 0,

                        count : 0,

                        max_count : 0,

                        current_product_all : {},

                        current_product : null,

                        current_product_type : [],

                        current_colors : []
                    }
                ];

                $("button[type='reset']").trigger('click');

                $('.select2_category').val('').trigger('change');

                $(".select2_category[multiple='multiple']" ).val(' ').trigger('change');

            },

            //切换类型的方法
            showType: function( e ){

                this.show_func_type = ( e.target.value == "2" );

                this.$nextTick( this.reSelect2 );

            },

            //select2初始化
            reSelect2: function reSelect2(){

                $('.function-type-selector').each( function(){

                    $(this).find('select').select2();

                });

            },

            //改变页数的时候出发的函数
            pageChange : function pageChange(val){

                this.search_info.page = val;

                this.search_info.per_page = this.query_info.per_page;

                this.getGlassList(this.search_info);

            },

            //改变每页显示数时触发的函数
            sizeChange : function sizeChange(val){

                this.search_info.per_page = val;

                this.query_info.per_page = val;

                this.getGlassList(this.search_info);

            },

            //点击搜索时触发的函数
            confirmSearch : function confirmSearch(){

                this.query_info.start_at = this.$refs.startTime.value;

                this.query_info.end_at = this.$refs.endTime.value;

                var json_object = JSON.stringify(this.query_info);

                this.search_info = JSON.parse(json_object);

                this.getGlassList(this.query_info);

            },

            //查看已添加的眼镜的信息详情
            glassDetail : function glassDetail(id){

                var self = this;

                self.watching_detail = true;

                self.current_glass = null;

                App.blockUI('#editor_form');

                glassResource.edit( id )
                            .then(function (res) {

                                if (parseInt(res.data.code) === 0) {

                                    self.current_glass = res.data.product;

                                    if( !self.current_glass.market_guidance_price ){

                                        $("#editor_form select[name='glasses_type']").val(self.current_glass.glasses_type).trigger('change');

                                        $("#editor_form select[name='function_type_id']").val(self.current_glass.function_type_id).trigger('change');

                                        $("#editor_form select[name='brand_id']").val(self.current_glass.brand_id).trigger('change');

                                        $("#editor_form select[name='gender']").val(self.current_glass.gender).trigger('change');

                                        $("#editor_form select[name='type_id']").val(self.current_glass.type_id).trigger('change');

                                        $("#editor_form select[name='mat_id']").val(self.current_glass.mat_id).trigger('change');

                                        $("#editor_form select[name='frame_id']").val(self.current_glass.frame_id).trigger('change');

                                        $("#editor_form select[name='color_ids[]']").val(self.current_glass['color_ids[]']).trigger('change');

                                        $("#editor_form select[name='style_ids[]']").val(self.current_glass['style_ids[]']).trigger('change');

                                        $("#editor_form select[name='function_ids[]']").val(self.current_glass['function_ids[]']).trigger('change');

                                        self.is_supplier = false;

                                    }else {

                                        $("#editor_form select[name='color_ids[]']").select2('data',{'text':self.current_glass['color_ids[]']});

                                        $("#editor_form select[name='style_ids[]']").select2('data',{'text':self.current_glass['style_ids[]']});

                                        $("#editor_form select[name='function_ids[]']").select2('data',{'text':self.current_glass['function_ids[]']});

                                        $("#editor_form select[name='glasses_type']").select2('data',{'text':self.current_glass.glasses_type});

                                        $("#editor_form select[name='function_type_id']").select2('data',{'text':self.current_glass.function_type_id});

                                        $("#editor_form select[name='brand_id']").select2('data',{'text':self.current_glass.brand_id});

                                        $("#editor_form select[name='gender']").select2('data',{'text':self.current_glass.gender});

                                        $("#editor_form select[name='type_id']").select2('data',{'text':self.current_glass.type_id});

                                        $("#editor_form select[name='mat_id']").select2('data',{'text':self.current_glass.mat_id});

                                        $("#editor_form select[name='frame_id']").select2('data',{'text':self.current_glass.frame_id});

                                        self.is_supplier = true;

                                    }

                                    if( parseInt(self.current_glass.has_rd) === 1 ){

                                        $("#editor_form select[name='rd_upper_limit']").val(self.current_glass.rd_upper_limit).trigger('change');
                                        $("#editor_form select[name='rd_lower_limit']").val(self.current_glass.rd_lower_limit).trigger('change');

                                        $("#editor_form select[name='as_upper_limit']").val(self.current_glass.as_upper_limit).trigger('change');
                                        $("#editor_form select[name='as_lower_limit']").val(self.current_glass.as_lower_limit).trigger('change');

                                        $("#editor_form select[name='axial_upper_limit']").val(self.current_glass.axial_upper_limit).trigger('change');
                                        $("#editor_form select[name='axial_lower_limit']").val(self.current_glass.axial_lower_limit).trigger('change');

                                    }

                                    if( self.current_glass.relate_product && self.current_glass.relate_product.length > 0 ){

                                        self.has_product = 1;

                                        self.combine_products = self.current_glass.relate_product;

                                        self.combine_products.forEach(function(e,index){

                                            $("#editor_form select[name='customer_type']").eq(2*index+1).val(e.customer_id).trigger('change');

                                            $("#editor_form select[name='product_type']").eq(2*index+1).val(e.relate_type).trigger('change');

                                            $("#editor_form select[name='relate_product']").eq(2*index+1).val(e.relate_product_id).trigger('change');

                                            $("#editor_form select[name='relate_product_color']").eq(2*index+1).val(e.color_id).trigger('change');

                                        });

                                    }

                                } else {

                                    alert(res.data.error);

                                }

                                App.unblockUI('#editor_form');

                            })
                            .catch(function (err) {

                                console.log(err);

                                App.unblockUI('#editor_form');

                                alert('网络异常！');

                            })

            },

            //保存数据
            glassPost : function glassPost(){

                var self = this;

                var params = new FormData(this.$refs.productSingle);

                App.blockUI('#product_single');

                glassResource.store( params )
                            .then(function (res) {

                                if (parseInt(res.data.code) === 0) {

                                    self.getGlassList(self.query_info);

                                    alert('添加成功！');

                                    App.unblockUI('#product_single');

                                    self.resetAllData();

                                } else {

                                    App.unblockUI('#product_single');

                                    alert(res.data.error);

                                }

                            })
                            .catch(function (err) {

                                console.log(err);

                                App.unblockUI('#product_single');

                                alert('网络异常！');

                            })

            },

            //更新数据
            glassUpdate : function glassUpdate(){

                var self = this;

                var params = new FormData(this.$refs.editorForm);

                App.blockUI('#editor_form');

                glassResource.update( self.current_glass.id , params )
                            .then(function (res) {

                                if (parseInt(res.data.code) === 0) {

                                    alert('更新成功！');

                                    $('.close').trigger('click');

                                } else {

                                    alert(res.data.error);

                                }

                                App.unblockUI('#editor_form');

                            })
                            .catch(function (err) {

                                console.log(err);

                                App.unblockUI('#editor_form');

                                alert('网络异常！');

                            })

            },

            //获取现有眼镜列表
            getGlassList : function getGlassList( params ){

                var self = this;

                App.blockUI('#glass_list');

                glassResource.index( params )
                            .then(function (res) {

                                if (parseInt(res.data.code) === 0) {

                                    self.products = res.data.products;

                                    self.products.per_page = parseInt(self.products.per_page);

                                    self.query_info.per_page = self.products.per_page;

                                    if( parseInt(res.data.customer_type) === 0 ){

                                        self.supplier_power = false;

                                    }else {

                                        self.supplier_power = true;

                                    }

                                } else {

                                    alert(res.data.error);

                                }

                                App.unblockUI('#glass_list');

                            })
                            .catch(function (err) {

                                console.log(err);

                                App.unblockUI('#glass_list');

                                alert('网络异常！');

                            })

            },

            //初始化获得需要的数据
            initGlassData : function initGlassData(){

                var self = this;

                App.blockUI('#product_single');

                return glassResource.create()
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            self.all_products = res.data.all_products;

                                            self.frame_types = res.data.frame_types;

                                            self.frames = res.data.frames;

                                            self.brands = res.data.brands;

                                            self.funcs = res.data.funcs;

                                            self.func_types = res.data.func_types;

                                            self.materials = res.data.materials;

                                            self.colors = res.data.colors;

                                            self.styles = res.data.styles;

                                            self.genders = res.data.genders;

                                            self.lenses = res.data.lenses;

                                            self.opto = res.data.opto;

                                        } else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#product_single');

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        App.unblockUI('#product_single');

                                        alert('网络异常！');

                                    })

            }

        },
        watch : {
            //监听是否有度数
            has_rd : function(){

                setTimeout(function(){

                    $('.degree-selector').each( function(){
                        $(this).find('select').select2();
                    });

                },30);

            },
            //监听是否带有组合镜片
            has_product : function(){

                setTimeout(function(){

                    $('.combine-products').each( function(){
                        $(this).find('select').select2();
                    });

                },30);

            },
            // 监听组合镜片的增删操作
            combine_products : function(){

                setTimeout(function(){

                    $('.combine-products').each( function(){
                        $(this).find('select').select2();
                    });

                },30);

            },
            //监听多选的颜色
            selected_color_ids : function(){

                var self = this;

                var selected_colors = [];

                if( !self.selected_color_ids ) {

                    self.current_glass.colors = null;

                    return;

                }

                self.selected_color_ids.forEach(function(e){

                    var selected_color = self.colors.filter(function(color){

                        return color.id == e;

                    })[0];

                    selected_color.pivot = {
                        product_id: '',
                        color_id: '',
                        stock: '',
                        stock_detail: '',
                        sku_code: ''
                    };

                    selected_colors.push(selected_color);

                });

                if( !self.watching_detail ){

                    self.current_glass.colors = selected_colors;

                }

            }
        }

    });

    $('.select-color').change(function(){

        _Global_Data.selected_color_ids = $(this).val();

    });

}();